package com.shopx.auth.service.impl;


import com.shopx.auth.service.ISysLoginTokenService;
import com.shopx.base.constants.ResultCodeEnum;
import com.shopx.base.exception.ShopxException;
import com.shopx.base.service.base.BaseService;
import com.shopx.core.utils.StringUtil;
import com.shopx.dal.redis.CacheServiceFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


/**
 * SysLoginToken
 *
 * @author lituo 2021-01-04
 */
@Service
@Slf4j
public class SysLoginTokenServiceImpl extends BaseService implements ISysLoginTokenService {

  /**
   * 令牌在redis中失效时间（秒）  30天失效
   */
  public static final Long TOKEN_EFF_TM = 2592000L;

  @Override
  public String selectByRedis(String userId, String userType) throws ShopxException {
    String key = userId + ":" + userType;
    String tokenId = (String)CacheServiceFactory.getCacheService().get(key);
    if(tokenId==null){
      throw new ShopxException(ResultCodeEnum.BUSI_TOKEN_INVALIDATE);
    }
    return tokenId;
  }


  @Override
  public void setUserTokensForRedis(String tokenId, String userType, String userId) throws ShopxException {
    if (StringUtil.isEmpty(tokenId) || StringUtil.isEmpty(userType) || StringUtil.isEmpty(userId)) {
      throw new ShopxException(ResultCodeEnum.PAR_NULL);
    }
    boolean result = CacheServiceFactory.getCacheService().set(userId + ":" + userType, tokenId,TOKEN_EFF_TM);
    if(!result){
      throw new ShopxException(ResultCodeEnum.BUSI_TOKEN_ERROR);
    }
  }

  @Override
  public boolean checkUserLogin(String userId, String userType, String tokenId) throws ShopxException {
    log.info("开始验证用户令牌.userId:{},userType:{},tokenId:{}", userId, userType, tokenId);
    String redisTokenId = selectByRedis(userId, userType);
    if (redisTokenId == null) {
      //不存在，过期或者本来就没有
      log.info("userId:{},userType:{}令牌不存在,拦截器拒绝", userId, userType);
      //清空缓存信息
      CacheServiceFactory.getCacheService().del(userId + ":" + userType);
      throw new ShopxException(ResultCodeEnum.BUSI_TOKEN_ERROR);
    }
    if (!tokenId.equals(redisTokenId)) {
      log.info("userId:{},userType:{}令牌不正确,拦截器拒绝", userId, userType);
      throw new ShopxException(ResultCodeEnum.BUSI_TOKEN_ERROR);
    }
    //更新令牌有效时长
    this.setUserTokensForRedis(tokenId,userType,userId);
    return true;
  }
}

